package com.block.datapush.special.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.service.LogFactory;
import com.block.common.vo.ResponseVo;
import com.block.datapush.common.model.result.FilterHandlerResult;
import com.block.datapush.common.service.ISpecialDataFilterHandlerService;
import com.block.datapush.model.result.SpePushResut;
import com.block.datapush.special.service.IDataPushSelfSpecialService;
import com.block.datapush.special.service.ISpecialCostomInfoService;
import com.block.datapush.special.utils.SpecialUtil;
import com.block.db.entity.MemberExtInfo;
import com.block.db.entity.SpecialCostomInfo;
import com.block.db.entity.SpecialCostomItemInfo;
import com.block.db.mapper.SpecialCostomItemInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 自采流量进行推送流程
 */
@Service
public class DataPushSelfSpecialService implements IDataPushSelfSpecialService {

    private static Logger log = LogFactory.getPushLog();

    @Resource
    SpecialCostomItemInfoMapper specialCostomItemInfoMapper;
    @Autowired
    ISpecialCostomInfoService specialCostomInfoService;
    @Autowired
    NotifyExceptionService notifyExceptionService;
    @Autowired
    ISpecialDataFilterHandlerService specialDataFilterHandlerService;

    /**
     * 数据撞库 流程
     *
     * @param memberExtInfo
     * @return
     */
    @Override
    public SpePushResut dataCheckHandle(MemberExtInfo memberExtInfo) {

        SpePushResut spePushResut = new SpePushResut();
        spePushResut.setPushSuccess(false);

        // 查询可推送的所有商户任务
        List<SpecialCostomItemInfo> costomItemInfoList = specialCostomItemInfoMapper.getFlowItemInfoList();

        List<SpecialCostomItemInfo> canPushItemList = new ArrayList<>();
        // 第一遍循环，推送任务过滤，找出可以推送的任务
        for (SpecialCostomItemInfo itemInfo: costomItemInfoList){
            /**
             * 根据任务设置的条件
             * 以及，用户填写的资质
             * 判断该用户资质是否满足该任务
             */
            FilterHandlerResult handlerResult = specialDataFilterHandlerService.execCondiFilter(itemInfo, memberExtInfo);
            if (handlerResult.isSuccess()){
                // 任务满足条件，则添加到可推送列表
                canPushItemList.add(itemInfo);
            }
        }

        // 如果可推送列表为空，则返回撞库失败
        if (CollUtil.isEmpty(canPushItemList)){
            // 没有满足条件可推送的任务
            spePushResut.setMessage("没有可推送的分流任务");
            return spePushResut;
        }

        // TODO: 2024/7/8 同步推送，需要改为异步推送
        for (SpecialCostomItemInfo itemInfo : canPushItemList) {
            try {
                spePushResut = specialCostomInfoService.checkUser(itemInfo, memberExtInfo);
                if (spePushResut.isPushSuccess()){
                    // 撞库成功，则返回机构相关信息
                    break;
                }
            }catch (Exception exception){
                exception.printStackTrace();
                notifyExceptionService.notifyException("","","","机构推送分流任务：" + memberExtInfo.getUid()+";"+itemInfo.getId(), exception);
            }
        }

        return spePushResut;
    }


    /**
     * 数据进件流程
     *
     * @param orderNo
     * @return
     */
    @Override
    public ResponseVo dataRegisterHandle(String orderNo) {

        try {
            /**
             * 推送的时候不判断商户的余额
             * 如果撞库成功，已经展示了商户的信息
             * 已经产生了消耗
             */
            SpePushResut spePushResut = specialCostomInfoService.registerUser(orderNo);
            return new ResponseVo(AppRspCodeConstant.SUCCESS, spePushResut);
        }catch (Exception exception){
            notifyExceptionService.notifyException("","","","机构推送异常：orderNo:" + orderNo, exception);
        }
        return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "", "进件异常");
    }

    /**
     * 撞库并且推送
     * 推送方式为 先 竞价  后分流
     * @param memberExtInfo
     * @return
     */
    @Override
    public SpePushResut dataPushHandle(MemberExtInfo memberExtInfo) {

        SpePushResut spePushResut = new SpePushResut();
        spePushResut.setPushSuccess(false);
        try {
            /**
             * 竞价模式推送
             */
            spePushResut = this.pushBiddItemInfo2(memberExtInfo);
            log.info("【机构推送】【竞价推送完成】【result】{}", spePushResut.isPushSuccess() );
            if (spePushResut.isPushSuccess()){
                return spePushResut;
            }

            /**
             * 分流任务 推送
             */
            spePushResut = this.pushFlowItemInfo(memberExtInfo);
            log.info("【机构推送】【分流推送完成】【result】{}", spePushResut.isPushSuccess() );

            return spePushResut;
        }catch (Exception exception){
            notifyExceptionService.notifyException("","","","机构推送异常：" + memberExtInfo.getUid(), exception);
        }
        return spePushResut;
    }

    /**
     * 分流任务推送  推送
     *
     * @param memberExtInfo
     * @return
     */
    public SpePushResut pushFlowItemInfo(MemberExtInfo memberExtInfo){

        List<SpecialCostomItemInfo> costomItemInfoList = specialCostomItemInfoMapper.getFlowItemInfoList();

        List<SpecialCostomItemInfo> canPushItemList = new ArrayList<>();
        // 第一遍循环，推送任务过滤，找出可以推送的任务
        for (SpecialCostomItemInfo itemInfo: costomItemInfoList){
            // 条件判断
            FilterHandlerResult handlerResult = specialDataFilterHandlerService.execCondiFilter(itemInfo, memberExtInfo);
            if (handlerResult.isSuccess()){
                // 可以推送的任务
                canPushItemList.add(itemInfo);
            }
        }

        SpePushResut spePushResut = new SpePushResut();
        spePushResut.setPushSuccess(false);
        if (CollUtil.isEmpty(canPushItemList)){
            // 没有满足条件可推送的任务
            spePushResut.setMessage("没有可推送的分流任务");
            return spePushResut;
        }

        SpecialCostomItemInfo itemInfo  = SpecialUtil.getCanPushItemInfo(canPushItemList);;
        while (true){
            // 根据
            try {
                spePushResut = specialCostomInfoService.checkAndRegisterUser(itemInfo, memberExtInfo);

            }catch (Exception exception){
                exception.printStackTrace();
                notifyExceptionService.notifyException("","","","机构推送分流任务：" + memberExtInfo.getUid()+";"+itemInfo.getId(), exception);
            }

            if (!spePushResut.isPushSuccess()){
                itemInfo = SpecialUtil.getCanPushItemInfo(canPushItemList);
                if (ObjectUtil.isEmpty(itemInfo)){
                    // 全部执行失败
                    break;
                }
            }else{
                break;
            }
        }

        return spePushResut;
    }

    /**
     * 竞价任务  第二种
     * 单城市 价格相同时，进行分流推送
     *
     * @param memberExtInfo
     * @return
     */
    public SpePushResut pushBiddItemInfo2(MemberExtInfo memberExtInfo){
        List<SpecialCostomItemInfo> costomItemInfoList = specialCostomItemInfoMapper.getBiddItemInfoList();

        List<SpecialCostomItemInfo> canPushItemList = new ArrayList<>();

        Map<BigDecimal, List<SpecialCostomItemInfo>> mapItemList = new HashMap<>();

        // 第一遍循环，推送任务过滤，找出可以推送的任务
        for (SpecialCostomItemInfo itemInfo: costomItemInfoList){
            // 条件判断
            FilterHandlerResult handlerResult = specialDataFilterHandlerService.execCondiFilter(itemInfo, memberExtInfo);
            if (handlerResult.isSuccess()){
                // 可以推送的任务
                canPushItemList.add(itemInfo);
                List<SpecialCostomItemInfo> itemInfoList = mapItemList.get(itemInfo.getPriceAmount());
                if (ObjectUtil.isEmpty(itemInfoList)){
                    itemInfoList = new ArrayList<>();
                }
                itemInfoList.add(itemInfo);

                mapItemList.put(itemInfo.getPriceAmount(), itemInfoList);
            }
        }

        SpePushResut spePushResut = new SpePushResut();
        spePushResut.setPushSuccess(false);
        if (CollUtil.isEmpty(canPushItemList)){
            // 没有满足条件可推送的任务
            spePushResut.setMessage("没有可推送的竞价任务");
            return spePushResut;
        }

       List<BigDecimal> priceList = JSON.parseArray(JSON.toJSONString(mapItemList.keySet()), BigDecimal.class);
        Collections.sort(priceList);
        Collections.reverse(priceList);

        for (BigDecimal bigDecimal : priceList) {
            List<SpecialCostomItemInfo> itemInfoList = mapItemList.get(bigDecimal);

            SpecialCostomItemInfo itemInfo  = SpecialUtil.getCanPushItemInfo(itemInfoList);;
            while (true){
                // 根据
                try {
                    spePushResut = specialCostomInfoService.checkAndRegisterUser(itemInfo, memberExtInfo);
                }catch (Exception exception){
                    exception.printStackTrace();
                    notifyExceptionService.notifyNoticeInfo("PUSH分流","机构推送分流任务：" , memberExtInfo.getUid()+";"+itemInfo.getId(), exception);
                }

                if (!spePushResut.isPushSuccess()){
                    itemInfo = SpecialUtil.getCanPushItemInfo(itemInfoList);
                    if (ObjectUtil.isEmpty(itemInfo)){
                        // 全部执行失败
                        break;
                    }
                }else{
                    break;
                }
            }

            if (spePushResut.isPushSuccess()){
                break;
            }
        }
        return spePushResut;
    }


    /**
     * 单独推送某个机构
     * 手动/代码推送
     * @param costomInfo
     * @param memberExtInfo
     * @return
     */
    @Override
    public ResponseVo dataPushSingleCostomInfo(SpecialCostomInfo costomInfo, MemberExtInfo memberExtInfo) {

        // 查询可用的机构信息
        List<SpecialCostomItemInfo> enableEntityList =
                specialCostomItemInfoMapper.getEnableEntityList(costomInfo.getId());
        if (CollUtil.isEmpty(enableEntityList)){
            return new ResponseVo(AppRspCodeConstant.DATA_INFO_NULL, "没有可推送的任务", "");
        }

        SpePushResut result = null;
        try {
            for (SpecialCostomItemInfo itemInfo: enableEntityList){
                FilterHandlerResult handlerResult = specialDataFilterHandlerService.execCondiFilter(itemInfo, memberExtInfo);

                if (handlerResult.isSuccess()){
                    result = specialCostomInfoService.checkAndRegisterUser(itemInfo, memberExtInfo);
                    if (result.isPushSuccess()){
                        break;
                    }
                }else{
                    result = new SpePushResut();
                    result.setPushSuccess(false);
                    result.setMessage(handlerResult.getMessage());
                }
            }
        }catch (Exception exception){
            exception.printStackTrace();
            return new ResponseVo(AppRspCodeConstant.DATA_INFO_NULL, "操作异常："+exception.getMessage(), "");
        }

        if (ObjectUtil.isEmpty(result)){
            return new ResponseVo(AppRspCodeConstant.DATA_INFO_NULL, "推送结果为空", "");
        }

        if (!result.isPushSuccess()){
            return new ResponseVo(AppRspCodeConstant.DATA_INFO_NULL, "推送失败："+result.getMessage(), "");
        }

        return new ResponseVo(AppRspCodeConstant.SUCCESS, result);
    }

}
